const path = require('path');
const ApiValidator = require('./api-validator');

/**
 * 配置管理模块 - 现代化JSON配置版本
 * 替代旧的.env文件配置系统
 */
class ConfigManager {
    constructor(projectRoot) {
        this.projectRoot = projectRoot;
        this.apiValidator = new ApiValidator();

        // 初始化JSON配置管理器
        const JsonConfigManager = require('./lib/config/json-config-manager');
        const ConfigPathResolver = require('./lib/config/config-path-resolver');

        const pathResolver = new ConfigPathResolver();
        this.jsonConfigManager = new JsonConfigManager(projectRoot);
        this.configPath = pathResolver.getConfigFilePath();
    }

    /**
     * 获取当前配置状态
     * @param {boolean} validateApi - 是否进行真实API验证 (默认false)
     * @returns {Object} 配置状态信息
     */
    async getConfigurationStatus(validateApi = false) {
        const status = {
            hasConfigFile: false,
            isConfigured: false,
            configuredProviders: [],
            currentProvider: null,
            placeholderIssues: [],
            missingConfigs: [],
            recommendations: [],
            apiValidation: validateApi ? {
                enabled: true,
                validatedProviders: [],
                invalidProviders: [],
                validationErrors: []
            } : {
                enabled: false
            }
        };

        try {
            // 检查JSON配置文件是否存在
            const config = this.jsonConfigManager.loadConfig();
            status.hasConfigFile = true;

            // 检查占位符 - 与web配置服务器保持一致
            const placeholderPatterns = [
                /your-.*-api-key-here/i,
                /你的.*api密钥/i,
                /sk-your-real-.*-key-here/i,
                /sk-test-demo-key/i,
                /test-api-key-demo/i,
                /your-real-.*-key-here/i,
                /demo/i,
                /example/i,
                /placeholder/i,
                /占位符/i,
                /请输入/i
            ];

            // 检查每个提供商的配置
            const providers = config.providers || {};
            for (const [providerName, providerConfig] of Object.entries(providers)) {
                if (providerConfig.api_key) {
                    // 检查API密钥是否为占位符
                    const isPlaceholder = placeholderPatterns.some(pattern =>
                        pattern.test(providerConfig.api_key)
                    );

                    if (isPlaceholder) {
                        status.placeholderIssues.push(`${providerName} API 密钥需要配置`);
                    } else {
                        // 检查是否看起来像真实的API密钥
                        let looksLikeRealKey = false;
                        if (providerName === 'zai') {
                            // 智谱AI使用特殊格式：xxx.yyyy
                            looksLikeRealKey = providerConfig.api_key.includes('.') &&
                                             providerConfig.api_key.length > 30 &&
                                             !providerConfig.api_key.includes('test') &&
                                             !providerConfig.api_key.includes('demo');
                        } else {
                            // 其他提供商通常使用sk-开头格式
                            looksLikeRealKey = providerConfig.api_key.startsWith('sk-') &&
                                                   providerConfig.api_key.length > 20 &&
                                                   !providerConfig.api_key.includes('test') &&
                                                   !providerConfig.api_key.includes('demo');
                        }

                        if (looksLikeRealKey) {
                            status.configuredProviders.push(providerName);

                            // 如果启用API验证，存储配置信息用于后续验证
                            if (validateApi) {
                                if (!status.pendingValidations) {
                                    status.pendingValidations = [];
                                }
                                status.pendingValidations.push({
                                    name: providerName,
                                    baseUrl: providerConfig.base,
                                    apiKey: providerConfig.api_key
                                });
                            }
                        }
                    }
                }
            }

            // 获取当前提供商
            status.currentProvider = config.current_provider || null;

            // 如果启用API验证，进行真实API调用验证
            if (validateApi && status.pendingValidations && status.pendingValidations.length > 0) {
                console.log('正在进行API密钥真实验证...');

                for (const providerConfig of status.pendingValidations) {
                    try {
                        console.log(`验证 ${providerConfig.name} 提供商...`);
                        const validationResult = await this.apiValidator.validateProvider(
                            providerConfig.name,
                            providerConfig.baseUrl,
                            providerConfig.apiKey
                        );

                        if (validationResult.success) {
                            status.apiValidation.validatedProviders.push({
                                name: providerConfig.name,
                                modelCount: validationResult.modelCount,
                                models: validationResult.models,
                                message: validationResult.message
                            });
                        } else {
                            status.apiValidation.invalidProviders.push({
                                name: providerConfig.name,
                                error: validationResult.error
                            });
                            // 从已配置提供商中移除无效的提供商
                            const index = status.configuredProviders.indexOf(providerConfig.name);
                            if (index > -1) {
                                status.configuredProviders.splice(index, 1);
                            }
                        }
                    } catch (error) {
                        status.apiValidation.validationErrors.push({
                            provider: providerConfig.name,
                            error: error.message
                        });
                        // 从已配置提供商中移除验证失败的提供商
                        const index = status.configuredProviders.indexOf(providerConfig.name);
                        if (index > -1) {
                            status.configuredProviders.splice(index, 1);
                        }
                    }
                }

                // 清理临时数据
                delete status.pendingValidations;
            }

            // 判断整体配置状态
            status.isConfigured = status.configuredProviders.length > 0 && status.placeholderIssues.length === 0;

            // 生成建议
            if (status.configuredProviders.length === 0) {
                status.recommendations.push('至少配置一个 LLM 服务商');
            }
            if (!status.currentProvider) {
                status.recommendations.push('设置当前提供商');
            }

        } catch (error) {
            status.recommendations.push('创建配置文件');
        }

        return status;
    }

    /**
     * 配置服务商
     * @param {string} providerName - 服务商名称
     * @param {string} apiKey - API 密钥
     * @param {boolean} setAsCurrent - 是否设为当前服务商
     * @returns {Object} 配置结果
     */
    async configureProvider(providerName, apiKey, setAsCurrent = true) {
        try {
            // 验证服务商名称
            const validProviders = ['moonshot', 'tencent', 'zai'];
            if (!validProviders.includes(providerName)) {
                return {
                    success: false,
                    error: `不支持的服务商: ${providerName}。支持的: ${validProviders.join(', ')}`
                };
            }

            // 验证API密钥
            if (!apiKey || apiKey.trim() === '') {
                return {
                    success: false,
                    error: 'API 密钥不能为空'
                };
            }

            // 获取服务商配置模板
            const providerConfigs = {
                moonshot: {
                    base: 'https://api.moonshot.cn/v1',
                    models: [
                        {
                            id: 'moonshot-v1-128k-vision-preview',
                            name: 'moonshot-v1-128k-vision-preview',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 128000,
                            supports_vision: true,
                            enabled: true
                        },
                        {
                            id: 'moonshot-v1-32k-vision-preview',
                            name: 'moonshot-v1-32k-vision-preview',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 32000,
                            supports_vision: true,
                            enabled: true
                        },
                        {
                            id: 'moonshot-v1-8k-vision-preview',
                            name: 'moonshot-v1-8k-vision-preview',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 8000,
                            supports_vision: true,
                            enabled: true
                        }
                    ]
                },
                tencent: {
                    base: 'https://api.hunyuan.cloud.tencent.com/v1',
                    models: [
                        {
                            id: 'hunyuan-t1-vision',
                            name: 'hunyuan-t1-vision',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 8192,
                            supports_vision: true,
                            enabled: true
                        },
                        {
                            id: 'hunyuan-vision',
                            name: 'hunyuan-vision',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 4096,
                            supports_vision: true,
                            enabled: true
                        }
                    ]
                },
                zai: {
                    base: 'https://open.bigmodel.cn/api/paas/v4',
                    models: [
                        {
                            id: 'glm-4.5v',
                            name: 'glm-4.5v',
                            type: 'vision',
                            capabilities: ['image_analysis'],
                            max_tokens: 8192,
                            supports_vision: true,
                            enabled: true
                        }
                    ]
                }
            };

            const configTemplate = providerConfigs[providerName];
            if (!configTemplate) {
                return {
                    success: false,
                    error: `找不到服务商 ${providerName} 的配置模板`
                };
            }

            // 构建提供商配置
            const providerConfig = {
                base: configTemplate.base,
                api_key: apiKey.trim(),
                models: configTemplate.models,
                timeout: 30000,
                max_retries: 3
            };

            // 加载现有配置
            let config;
            try {
                config = this.jsonConfigManager.loadConfig();
            } catch (error) {
                // 如果配置文件不存在，创建默认配置
                config = {
                    providers: {},
                    current_provider: null,
                    settings: {
                        log_level: 'info',
                        max_concurrent_requests: 5,
                        request_timeout: 30000
                    }
                };
            }

            // 更新提供商配置
            config.providers[providerName] = providerConfig;

            // 设置为当前提供商（如果需要）
            if (setAsCurrent) {
                config.current_provider = providerName;
            }

            // 保存配置
            this.jsonConfigManager.saveConfig(config);

            return {
                success: true,
                provider: providerName,
                apiKey: '***' + apiKey.slice(-4), // 只显示最后4位
                setAsCurrent,
                message: `成功配置 ${providerName} 服务商`
            };

        } catch (error) {
            return {
                success: false,
                error: `配置失败: ${error.message}`
            };
        }
    }

    /**
     * 切换当前使用的服务商
     * @param {string} providerName - 服务商名称
     * @returns {Object} 切换结果
     */
    async switchProvider(providerName) {
        try {
            const config = this.jsonConfigManager.loadConfig();

            if (!config.providers || !config.providers[providerName]) {
                return {
                    success: false,
                    error: `服务商 ${providerName} 尚未配置。已配置的服务商: ${Object.keys(config.providers || {}).join(', ')}`
                };
            }

            config.current_provider = providerName;
            this.jsonConfigManager.saveConfig(config);

            return {
                success: true,
                currentProvider: providerName,
                message: `已切换到 ${providerName} 服务商`
            };

        } catch (error) {
            return {
                success: false,
                error: `切换失败: ${error.message}`
            };
        }
    }

    /**
     * 删除服务商配置
     * @param {string} providerName - 服务商名称
     * @returns {Object} 删除结果
     */
    async removeProvider(providerName) {
        try {
            const config = this.jsonConfigManager.loadConfig();

            if (!config.providers || !config.providers[providerName]) {
                return {
                    success: false,
                    error: `服务商 ${providerName} 未配置`
                };
            }

            // 删除提供商配置
            delete config.providers[providerName];

            // 如果删除的是当前提供商，需要切换到其他提供商
            if (config.current_provider === providerName) {
                const remainingProviders = Object.keys(config.providers);
                if (remainingProviders.length > 0) {
                    config.current_provider = remainingProviders[0];
                } else {
                    config.current_provider = null;
                }
            }

            this.jsonConfigManager.saveConfig(config);

            return {
                success: true,
                removedProvider: providerName,
                message: `已删除 ${providerName} 服务商配置`
            };

        } catch (error) {
            return {
                success: false,
                error: `删除失败: ${error.message}`
            };
        }
    }

    /**
     * 获取服务商注册链接
     * @param {string} providerName - 服务商名称
     * @returns {Object} 注册信息
     */
    getProviderInfo(providerName) {
        const providers = {
            moonshot: {
                name: 'Moonshot (月之暗面)',
                signupUrl: 'https://platform.moonshot.cn/',
                description: '支持多轮对话的AI助手，提供强大的视觉理解能力',
                pricingUrl: 'https://platform.moonshot.cn/pricing'
            },
            tencent: {
                name: '腾讯混元',
                signupUrl: 'https://console.cloud.tencent.com/hunyuan',
                description: '腾讯出品的混元大模型，适合中文场景，性能优秀',
                pricingUrl: 'https://cloud.tencent.com/document/product/1729/104753'
            },
            zai: {
                name: '智谱AI (GLM)',
                signupUrl: 'https://open.bigmodel.cn/',
                description: '清华智谱AI的GLM系列模型，GLM-4.5v具有优秀的视觉理解能力',
                pricingUrl: 'https://open.bigmodel.cn/pricing'
            }
        };

        return providers[providerName] || null;
    }

    /**
     * 生成配置报告
     * @returns {string} 格式化的配置报告
     */
    async generateConfigurationReport(status = null) {
        // 如果没有传入status，则同步获取（不进行API验证）
        if (!status) {
            status = await this.getConfigurationStatus(false);
        }
        const reports = [];

        if (!status.hasConfigFile) {
            reports.push('📋 配置文件不存在');
            reports.push('建议运行配置向导开始设置');
            return reports.join('\n');
        }

        reports.push('📊 当前配置状态:\n');

        if (status.isConfigured) {
            reports.push('✅ 配置完整');
            reports.push(`🎯 当前服务商: ${status.currentProvider || '未设置'}`);
            reports.push(`🔧 已配置服务商: ${status.configuredProviders.join(', ') || '无'}`);
        } else {
            reports.push('⚠️  配置不完整');

            if (status.placeholderIssues.length > 0) {
                reports.push('\n🔧 需要配置的API密钥:');
                status.placeholderIssues.forEach(issue => {
                    reports.push(`   • ${issue}`);
                });
            }

            if (status.missingConfigs.length > 0) {
                reports.push('\n❌ 缺失的配置:');
                status.missingConfigs.forEach(config => {
                    reports.push(`   • ${config}`);
                });
            }
        }

        // 添加API验证结果（如果有）
        if (status.apiValidation && status.apiValidation.enabled) {
            reports.push('\n🔍 API密钥验证结果:');

            if (status.apiValidation.validatedProviders.length > 0) {
                reports.push('   ✅ 验证通过的提供商:');
                status.apiValidation.validatedProviders.forEach(provider => {
                    reports.push(`      • ${provider.name}: ${provider.modelCount}个模型可用`);
                });
            }

            if (status.apiValidation.invalidProviders.length > 0) {
                reports.push('   ❌ 验证失败的提供商:');
                status.apiValidation.invalidProviders.forEach(provider => {
                    reports.push(`      • ${provider.name}: ${provider.error}`);
                });
            }

            if (status.apiValidation.validationErrors.length > 0) {
                reports.push('   ⚠️  验证出错的提供商:');
                status.apiValidation.validationErrors.forEach(error => {
                    reports.push(`      • ${error.provider}: ${error.error}`);
                });
            }

            if (status.apiValidation.validatedProviders.length === 0 &&
                status.apiValidation.invalidProviders.length === 0 &&
                status.apiValidation.validationErrors.length === 0) {
                reports.push('   ℹ️  未进行API验证');
            }
        }

        if (status.recommendations.length > 0) {
            reports.push('\n💡 建议:');
            status.recommendations.forEach(rec => {
                reports.push(`   • ${rec}`);
            });
        }

        return reports.join('\n');
    }
}

/**
 * 创建演示配置文件
 * @param {string} projectRoot - 项目根目录
 * @returns {boolean} - 是否成功创建
 */
function createDemoConfig(projectRoot) {
    const JsonConfigManager = require('./lib/config/json-config-manager');
    const ConfigPathResolver = require('./lib/config/config-path-resolver');

    const pathResolver = new ConfigPathResolver();
    const configManager = new JsonConfigManager(projectRoot);

    const demoConfig = {
        providers: {
            moonshot: {
                base: "https://api.moonshot.cn/v1",
                api_key: "sk-your-real-moonshot-key-here",
                models: [
                    {
                        id: "moonshot-v1-8k-vision-preview",
                        name: "moonshot-v1-8k-vision-preview",
                        type: "vision",
                        capabilities: ["image_analysis"],
                        max_tokens: 8000,
                        supports_vision: true,
                        enabled: true
                    }
                ],
                timeout: 30000,
                max_retries: 3
            },
            tencent: {
                base: "https://api.hunyuan.cloud.tencent.com/v1",
                api_key: "sk-your-real-tencent-key-here",
                models: [
                    {
                        id: "hunyuan-vision",
                        name: "hunyuan-vision",
                        type: "vision",
                        capabilities: ["image_analysis"],
                        max_tokens: 4096,
                        supports_vision: true,
                        enabled: true
                    }
                ],
                timeout: 30000,
                max_retries: 3
            },
            zai: {
                base: "https://open.bigmodel.cn/api/paas/v4",
                api_key: "your-real-zhipu-key-here",
                models: [
                    {
                        id: "glm-4.5v",
                        name: "glm-4.5v",
                        type: "vision",
                        capabilities: ["image_analysis"],
                        max_tokens: 8192,
                        supports_vision: true,
                        enabled: true
                    }
                ],
                timeout: 30000,
                max_retries: 3
            }
        },
        current_provider: "moonshot",
        settings: {
            log_level: "info",
            max_concurrent_requests: 5,
            request_timeout: 30000
        }
    };

    try {
        configManager.saveConfig(demoConfig);
        console.log('✅ 已创建演示配置文件');
        return true;
    } catch (error) {
        console.error('创建演示配置文件失败:', error.message);
        return false;
    }
}

module.exports = ConfigManager;
module.exports.createDemoConfig = createDemoConfig;